package com.lb.jwitter.service;

import java.io.Serializable;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.jws.WebService;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.lb.jwitter.*;
import com.lb.jwitter.hibernate.*;
import com.lb.jwitter.util.ChumanoLogger;
import com.lb.jwitter.util.ConditionReport;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JSONSerializer;

@Service("tbl_CTDT_MonHoc_TienQuyetService")
@Transactional
@WebService(endpointInterface = "com.lb.jwitter.service.Tbl_CTDT_MonHoc_TienQuyetService")
public class Tbl_CTDT_MonHoc_TienQuyetServiceImpl implements
		Tbl_CTDT_MonHoc_TienQuyetService, Serializable {

	private Log log = LogFactory
			.getLog(Tbl_CTDT_MonHoc_TienQuyetServiceImpl.class);
	private static final long serialVersionUID = -8740095022264495229L;

	@Autowired
	@Qualifier("tbl_CTDT_MonHoc_TienQuyetDAO")
	private Tbl_CTDT_MonHoc_TienQuyetDAO _tbl_CTDT_MonHoc_TienQuyetDao;

	@Autowired
	@Qualifier("tbl_CTDT_MonHocDAO")
	private Tbl_CTDT_MonHocDAO _tbl_CTDT_MonHocDao;
	
	@Autowired
	@Qualifier("tbl_CTDT_KhoiNganhDAO")
	private Tbl_CTDT_KhoiNganhDAO _tbl_CTDT_KhoiNganhDao;

	public final List<Tbl_CTDT_MonHoc_TienQuyet> findAlltbl_CTDT_MonHoc_TienQuyet(
			int pageSize, int page) {
		List<Tbl_CTDT_MonHoc_TienQuyet> result = get_tbl_CTDT_MonHoc_TienQuyetDao()
				.findAll(pageSize, page);
		log.info("Number of user in DB:: " + result.size());
		return result;
	}

	@Transactional(noRollbackFor = IllegalArgumentException.class)
	public final Long createtbl_CTDT_MonHoc_TienQuyet(
			Tbl_CTDT_MonHoc_TienQuyet obj) {
		return _tbl_CTDT_MonHoc_TienQuyetDao.save(obj);
	}

	public final void updatetbl_CTDT_MonHoc_TienQuyet(
			Tbl_CTDT_MonHoc_TienQuyet obj) {
		_tbl_CTDT_MonHoc_TienQuyetDao.update(obj);
	}// end update methode

	public final Tbl_CTDT_MonHoc_TienQuyet gettbl_CTDT_MonHoc_TienQuyet(Long id) {
		log.info("Try to retrieve the tbl_CTDT_MonHoc_TienQuyet: " + id);
		return get_tbl_CTDT_MonHoc_TienQuyetDao().get(id);
	}

	public void deletetbl_CTDT_MonHoc_TienQuyet(Long id) {
		log.info("Try to delete the tbl_CTDT_MonHoc_TienQuyet by Id : " + id);
		if (_tbl_CTDT_MonHoc_TienQuyetDao.exists(id)) {
			_tbl_CTDT_MonHoc_TienQuyetDao.delete(id);
		} else {
			throw new IllegalArgumentException("EmployeeId '" + id
					+ "' does not exists");
		}
	}

	public void deleteListtbl_CTDT_MonHoc_TienQuyet(String[] listId) {
		for (String id : listId) {
			deletetbl_CTDT_MonHoc_TienQuyet(Long.parseLong(id));
		}
	}

	public List<Tbl_CTDT_MonHoc_TienQuyet> findtbl_CTDT_MonHoc_TienQuyetByCondition(
			List<ConditionReport> cons, int pageSize, int page) {
		return _tbl_CTDT_MonHoc_TienQuyetDao.findByCondition(
				Tbl_CTDT_MonHoc_TienQuyet.class, cons, pageSize, page);
	}

	public int counttbl_CTDT_MonHoc_TienQuyetByCondition(
			List<ConditionReport> cons) {
		return _tbl_CTDT_MonHoc_TienQuyetDao.countByCondition(
				Tbl_CTDT_MonHoc_TienQuyet.class, cons);
	}

	public final Tbl_CTDT_MonHoc_TienQuyetDAO get_tbl_CTDT_MonHoc_TienQuyetDao() {
		return _tbl_CTDT_MonHoc_TienQuyetDao;
	}

	public final void set_tbl_CTDT_MonHoc_TienQuyetDao(
			Tbl_CTDT_MonHoc_TienQuyetDAO obj) {
		this._tbl_CTDT_MonHoc_TienQuyetDao = obj;
	}

	public Tbl_CTDT_MonHocDAO get_tbl_CTDT_MonHocDao() {
		return _tbl_CTDT_MonHocDao;
	}

	public void set_tbl_CTDT_MonHocDao(Tbl_CTDT_MonHocDAO _tbl_CTDT_MonHocDao) {
		this._tbl_CTDT_MonHocDao = _tbl_CTDT_MonHocDao;
	}

	public void createListtbl_CTDT_MonHoc_TienQuyetByJSON(String data) {
		try {
			ChumanoLogger.init(Tbl_CTDT_MonHoc_TienQuyetServiceImpl.class.getName());
			ChumanoLogger.log("0BAT DAU INSERT DU LIEU");
			List<Tbl_CTDT_MonHoc_TienQuyet> tbl_CTDT_MonHoc_TQs = new ArrayList<Tbl_CTDT_MonHoc_TienQuyet>();

			JSONArray jsons = (JSONArray) JSONSerializer.toJSON(data);
			ArrayList<String> notMonHocs = new ArrayList<String>();
			ArrayList<String> notKhoiNganhs = new ArrayList<String>();
			
			for (int i = 0; i < jsons.size(); i++) {
				String logStr ="";	
				JSONObject obj = jsons.getJSONObject(i);
				//MONHOC MONHOCTQ LOAITQ KHOINGANH
				// -----------------Lay du lieu--------------------------
				// ma
				String maMonHoc = obj.getString("MONHOC");

				// ten
				String maMonHocTQ = obj.getString("MONHOCTQ");

				// loai 2:TT , 1:SS , .:TQ
				String l = obj.getString("LOAITQ");
				String loai = (l.equals("1"))? "SH" : ((l.equals("2"))? "HT" :"TQ"  );
				
				// khoinganh
				String maKhoiNganh = obj.getString("MAKHOI");
				
				logStr ="[ " + (i+1)+ " - " 
				+ "MAMH: " + maMonHoc + " - " 
				+ "MAMHTQ: " + maMonHocTQ + " - " 
				+ "LOAITQ0: " + l + " - " 
				+ "LOAITQ: " + loai + " - " 
				+ "KHOI: " + maKhoiNganh
				+ "]";
				// ======================================================
				// tim mon hoc
				List<Long> monHocId = findMonHocId(maMonHoc);
				if (monHocId == null || monHocId.size() == 0) {
					ChumanoLogger.log(logStr + " NOT MAMH");
					if(!notMonHocs.contains(maMonHoc)) notMonHocs.add(maMonHoc);
					continue;
				}
				Tbl_CTDT_MonHoc  monhoc1 = new Tbl_CTDT_MonHoc();
				monhoc1.setId(monHocId.get(0));

				List<Long> monHocIdTQ = findMonHocId(maMonHocTQ);
				if (monHocIdTQ == null || monHocIdTQ.size() == 0) {
					ChumanoLogger.log(logStr + " NOT MAMHTQ");
					if(!notMonHocs.contains(maMonHocTQ)) notMonHocs.add(maMonHocTQ);
					continue;
				}
				Tbl_CTDT_MonHoc  monhoc2 = new Tbl_CTDT_MonHoc();
				monhoc2.setId(monHocIdTQ.get(0));
				
				// tim khoi nganh
				Tbl_CTDT_KhoiNganh khoinganh = null;
				if(!maKhoiNganh.equals("")){
					List<Long> khoiNganhIds = findKhoiNganhId(maKhoiNganh);
					if (khoiNganhIds != null && khoiNganhIds.size() > 0) {
						khoinganh = new Tbl_CTDT_KhoiNganh();
						khoinganh.setId(khoiNganhIds.get(0));
					}else{
						ChumanoLogger.log(logStr + " NOT KHOINGANH");
						if(!notKhoiNganhs.contains(maKhoiNganh)) notKhoiNganhs.add(maKhoiNganh);
						continue;
					}
				}
				
				//-----------------------------------------------------
				Tbl_CTDT_MonHoc_TienQuyet tbl_CTDT_MonHocTQ = new Tbl_CTDT_MonHoc_TienQuyet();
				List<Long> ids = findMonHocTQId(monHocId.get(0),monHocIdTQ.get(0), khoinganh);
				if (ids != null && ids.size() > 0) {
					tbl_CTDT_MonHocTQ.setId(ids.get(0));
					logStr+= " UPDATE";
				}else{
					logStr+= " INSERT";
				}
				
				tbl_CTDT_MonHocTQ.setMa(loai);
				tbl_CTDT_MonHocTQ.setMonHoc1Id(monhoc1);
				tbl_CTDT_MonHocTQ.setMonHoc2Id(monhoc2);
				tbl_CTDT_MonHocTQ.setKhoiNganhId(khoinganh);
				
				tbl_CTDT_MonHoc_TQs.add(tbl_CTDT_MonHocTQ);
				
				ChumanoLogger.log(logStr);

			}// end for
			_tbl_CTDT_MonHoc_TienQuyetDao.saveOrUpdateAll(tbl_CTDT_MonHoc_TQs);
			
			ChumanoLogger.log("===================== not monhoc=======================");
			reportArrayString(notMonHocs);
			ChumanoLogger.log("===================== not khoinganh=======================");
			reportArrayString(notKhoiNganhs);
			
		} catch (Exception e) {
			ChumanoLogger.log("ERROR: " +e.getMessage());
			System.out.println("------------ERROR CHUMANO-------------");
			e.printStackTrace();
			System.out.println("=================================");
		}
		ChumanoLogger.stop();
	}
	
	static void reportArrayString(ArrayList<String> arr){
		int i =1;
		for(String str :arr){
			ChumanoLogger.log(i + ". " + str);
			i++;
		}
	}

	private List<Long> findMonHocId(String maMonHoc) {
		List<ConditionReport> cons = new ArrayList<ConditionReport>();
		{
			ConditionReport con = new ConditionReport();
			con.setCol("ma");
			con.setValue1(maMonHoc);
			con.setOperator("eq");
			cons.add(con);
		}
		List<String> columns = new ArrayList<String>();
		columns.add("id");

		List<Long> monHocId = _tbl_CTDT_MonHocDao.findColumnByCondition(
				Tbl_CTDT_MonHoc.class, cons, columns, 1, 1);
		return monHocId;
	}
	
	private List<Long> findMonHocTQId(Long monhocId, Long monhocTQId, Tbl_CTDT_KhoiNganh khoinganh) {
		List<ConditionReport> cons = new ArrayList<ConditionReport>();
		{
			ConditionReport con = new ConditionReport();
			con.setCol("monHoc1Id.id");
			con.setValue1(monhocId);
			con.setOperator("eq");
			cons.add(con);
		}
		
		{
			ConditionReport con = new ConditionReport();
			con.setCol("monHoc2Id.id");
			con.setValue1(monhocTQId);
			con.setOperator("eq");
			cons.add(con);
		}
		
		{
			ConditionReport con = new ConditionReport();
			if(khoinganh==null){
				con.setCol("khoiNganhId");
//				con.setValue1(null);
				con.setOperator("isNull");
			}
			else{
				con.setCol("khoiNganhId.id");
				con.setValue1(khoinganh.getId());
				con.setOperator("eq");
			}
			
			cons.add(con);
		}
		List<String> columns = new ArrayList<String>();
		columns.add("id");

		List<Long> Ids = _tbl_CTDT_MonHoc_TienQuyetDao.findColumnByCondition(Tbl_CTDT_MonHoc_TienQuyet.class, cons, columns, 1, 1);
		return Ids;
	}

	private List<Long> findKhoiNganhId(String maKhoi) {
		List<ConditionReport> cons = new ArrayList<ConditionReport>();
		{
			ConditionReport con = new ConditionReport();
			con.setCol("ma");
			con.setValue1(maKhoi);
			con.setOperator("eq");
			cons.add(con);
		}
		List<String> columns = new ArrayList<String>();
		columns.add("id");

		List<Long> Ids = _tbl_CTDT_KhoiNganhDao.findColumnByCondition(
				Tbl_CTDT_KhoiNganh.class, cons, columns, 1, 1);
		return Ids;
	}
	
}// endclass

